/**
 * FileName: SpikeServiceImpl
 *
 * @author: 阿张
 * Date:     2021/2/25 14:27
 */
package com.qx.service;

import com.qx.mapper.ScDeployMapper;
import com.qx.pojo.ScDeploy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class SpikeServiceImpl implements SpikeService {

    @Resource
    private ScDeployMapper scDeployMapper;

    @Resource
    private RedisTemplate<String, Integer> redisTemplate;

    /**
     * 0未开始  1已开始  2已结束
     * */
    @Override
    public boolean deployStatus(Integer id) {
        ScDeploy scDeploy = scDeployMapper.selectById(id);
        if (Objects.nonNull(scDeploy)){
            if (scDeploy.getStatus() != null){
                Integer status = scDeploy.getStatus();
                return status == 1;
            }
            return false;
        }else {
            return false;
        }
    }


    @Override
    public boolean bought(Integer uid,Integer sid){
        Integer num = redisTemplate.opsForValue().get("ms" + uid + sid);

        return Objects.isNull(num);
    }


    @Override
    public boolean getCommodity(Integer uid, Integer sid){
        Integer num = redisTemplate.opsForValue().get("XSMS" + sid);
        if (num - 1 >= 0){
            redisTemplate.opsForValue().set("XSMS" + sid,num - 1);
            redisTemplate.opsForValue().set("ms" + uid + sid,1);
            return true;
        }
        return false;
    }

    @Override
    public boolean addSpikeCommodity(Integer id, Integer sid){
        Integer uid = 1;
        if (deployStatus(id)){
            if (bought(uid, sid)){
                return getCommodity(uid, sid);
            }
            return false;
        }
        return false;
    }
}
